var express = require('express');
var router = express.Router();
var err = require('../my_modules/error.js');
var config = require('../config');
var fs = require('fs');
var path = require('path');
var Busboy = require('busboy');
var schedule = require('node-schedule');


/*
定时清理临时文件夹
schedule 参数示例：
    每分钟的第30秒触发： '30 * * * * *'
    每小时的1分30秒触发 ：'30 1 * * * *'
    每天的凌晨1点1分30秒触发 ：'30 1 1 * * *'
    每月的1日1点1分30秒触发 ：'30 1 1 1 * *'
    2016年的1月1日1点1分30秒触发 ：'30 1 1 1 2016 *'
    每周1的1点1分30秒触发 ：'30 1 1 * * 1'
* */
schedule.scheduleJob('0 0 2 * * *',()=>{
    var search = function (dir) {
        var names = fs.readdirSync(dir);
        names.forEach(function (_name) {
            var state = fs.statSync(path.join(dir,_name));
            if(state.isDirectory()){
                search(path.join(dir,_name));
            }else{
                if(new Date().getTime() - new Date(state.ctime).getTime() > 1800000) {
                    fs.unlinkSync(path.join(dir,_name))
                }
            }
        })
    };
    search(path.resolve('./temp'));
});
var tcpCallback = null;
/*
* 上传成功返回空
* */
router.get('/void', function(req, res) {
    res.json();
});
/*
* 上传文件到临时文件夹
* */
router.post('/',function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename) {
        var saveTo = path.join('./temp/', path.basename(filename));
        file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', function () {
        res.writeHead(303, { Connection: 'close', Location: '/live/void' });
        res.end();
    });
    return req.pipe(busboy);
});
/*
* 查询文件列表
* 默认图片（img）
* */
router.get('/', function (req, res) {
    var data = req.query;
    var limit = data.limit*1 || 10;
    var offset = data.offset*1 || 0;
    if(!client) {
        res.json({
            count: 0,
            rows: []
        });
        return;
    }
    tcpCallback = function(data) {
        try {
            data = JSON.parse(data);
        }catch(e){
            data = err.serverErr;
        }
        res.json(data);
        tcpCallback = null;
    };
    sendCommand(JSON.stringify({
        command: 'list',
        limit: limit,
        offset: offset,
        search: data.search || 0,
        scape: data.scape || 0
    }));
});
/*
* 查询一个目录下的所有文件
* */
router.get('/allFiles', function(req, res){
    var data = req.query;
    if(!data.dir) {
        res.json(err.paraErr);
        return;
    }
    tcpCallback = function(data) {
        try {
            data = JSON.parse(data);
        }catch(e){
            data = err.serverErr;
        }
        res.json(data);
        tcpCallback = null;
    };
    sendCommand(JSON.stringify({
        command: 'allFiles',
        dir: data.dir,
    }));
});
/*
* 返回临时图片或向Slave索取图片
* */
router.get('/img', function(req, res){
    var data = req.query;
    if(!data.dir || !data.name) {
        res.json(err.paraErr);
        return;
    }
    var filePath = path.resolve('./temp/'+data.name);
    if(fs.existsSync(filePath)) {
        res.download(filePath);
        return;
    }
    sendCommand(JSON.stringify({
        command: 'picture',
        dir: data.dir,
        name: data.name
    }));
    res.redirect('/images/error404.png');
});
/*
* 返回临时图片或向Slave索取图片
* */
router.get('/videoDetail', function(req, res){
    var data = req.query;
    if(!data.dir || !data.name) {
        res.json(err.paraErr);
        return;
    }
    tcpCallback = function(data) {
        try {
            data = JSON.parse(data);
        }catch(e){
            data = err.serverErr;
        }
        res.json(data);
        tcpCallback = null;
    };
    sendCommand(JSON.stringify({
        command: 'videoDetail',
        dir: data.dir,
        name: data.name
    }));
});
/*
* 生成房间
* */
router.get('/house/:name', function (req, res) {
    if(!req.query.host || !req.query.dir || !req.query.name) {
        res.json(err.paraErr);
        return;
    }
    res.render('live.ejs', {
        host: req.query.host,
        channel: req.params.name,
        dir: req.query.dir,
        filename: req.query.name
    })
});
/*
* 播放视频
* */
router.post('/video', function (req, res) {
    var data = req.body;
    if(!data.dir || !data.name) {
        res.json(err.paraErr);
        return;
    }
    tcpCallback = function(data) {
        try {
            data = JSON.parse(data);
        }catch(e){
            data = err.serverErr;
        }
        res.json(data);
        tcpCallback = null;
    };
    var options = {
        command: 'play',
        dir: data.dir,
        name: data.name,
        seek: data.seek || 0
    };
    if(data.scale) {
        options.scale = data.scale*1;
    }
    sendCommand(JSON.stringify(options));
});
/*
* 关闭视频流
* */
router.delete('/video/:name', function (req, res) {
    tcpCallback = function(data) {
        try {
            data = JSON.parse(data);
        }catch(e){
            data = err.serverErr;
        }
        res.json(data);
        tcpCallback = null;
    };
    sendCommand(JSON.stringify({
        command: 'stop',
        channelName: req.params.name
    }));
});

module.exports = router;
var conf = require('../config').media;

//轮训API，关闭无人房间
var request = require('request');
var checkTimer = 0;
var checkHouses = function(){
    request('http://'+conf.tcpServerHost+':'+conf.http+'/api/streams', function(e,r,body){
        if(!body) return;
        var streams = null;
        try {
            streams = JSON.parse(body)
        } catch (e) { console.log(e); return;}
        var onLive = streams.live;
        for(var name in onLive) {
            if(onLive[name].subscribers.length === 0) {
                sendCommand(JSON.stringify({
                    command: 'stop',
                    channelName: name
                }));
            }
        }
    });
};

var net = require('net');
//创建TCP客户端
var client = new net.Socket();
var reconnectCount = 0;
var reconnectInterval = 5000;
client.setEncoding('utf8');
client.setNoDelay(true);
var getConnect = function(){
    reconnectCount++;
    if(reconnectCount === 5) reconnectInterval *= 2;
    else if(reconnectCount === 20) reconnectInterval *= 2;
    else if(reconnectCount === 50) reconnectInterval *= 60;
    client.connect(conf.tcpServerPort, conf.tcpServerHost, function () {
        console.log('已连接到服务器');
        reconnectCount = 0;
        client.write('Client');
        checkTimer = setInterval(checkHouses, 600000);
    });
};
client.on('data',function (data) {
    if(typeof(tcpCallback) === 'function') {
        tcpCallback(data.toString())
    }
});
//监听与服务端连接的错误事件
client.on('error',function (err) {
    console.log('在于服务器连接或通信过程中发生了一个错误，错误代码为%s', err.code);
    setTimeout(getConnect, reconnectInterval);
    clearInterval(checkTimer)
});
getConnect();

var commandList = [];
var sendList = function (list) {
    if(list.length === 0) {
        return;
    }
    client.write(list.shift(), function(){
        sendList(list);
    })
}
var sendCommand = function (c) {
    commandList.push(c);
    if(commandList.length === 1){
        sendList(commandList);
    }
};